<?php
declare (strict_types = 1);

namespace app\controller\clean;
use \Exception;
use think\exception\ValidateException;
use app\BaseController;
use app\logic\FileLogic;
use app\logic\ProjectLogic;
use app\model\HandleProject;
use app\model\HandleProjectCases;
use think\exception\Handle;
use think\facade\Db;

class Projects extends BaseController
{

    public function __construct(\think\App $app){
        parent::__construct($app);
    }

    protected function initialize() {
        parent::initialize();
        $action = $this->request->action();
        if ($action !== 'index') { // 检查当前项目名称
            $uuid = $this->request->param('_uuid_');
            $info = ProjectLogic::ins()->getProjectInfo($uuid);
            if (empty($info)) {
                echo json_encode(['code'=>0,'msg'=>'未知项目名称init'],JSON_UNESCAPED_UNICODE);exit;
            }
            $this->request->fhUuid = $info['uuid'];
            $this->request->fhTitle = $info['title'];
        }
    }

    /**
     * 清洗批次列表
     * @return \think\response\Json
     */
    public function list()
    {
        $list = ProjectLogic::ins()->getProjectList();
        return json($list);
    }

    /**
     * 添加清洗批次
     * @return \think\response\Json
     */
    public function add()
    {
        $title = $this->request->param('title/s', '', 'trim');
        $msg = ProjectLogic::ins()->addProject( $title);

        return json($msg);
    }

    /**
     * 上传清洗批次要素表 | 下载简要要素表模版
     * @return \think\response\Json
     */
    public function uploadCasesDetail() 
    {
        // 优先下载简要要素表模版
        if ($this->request->param('download') === 'tpl') {
            $data = [['甲方标识','姓名','身份证号码','联系电话','资金方','承办律师','律师']];
            FileLogic::ins()->downExeclFile($data, '待清洗案件要素表模板-' . date('YmdHis'));
            exit();
        }
        
        try {
            $file = $this->request->file('file');
            if (!$file->isValid()) {
                return json(['code'=>0,'msg'=>'上传失败']);
            }
        } catch (\Throwable $e) {
            return json(['code'=>0,'msg'=>$e->getMessage()]);
        }
        
        $extension = $file->getOriginalExtension();
        if ($extension !== 'xlsx') {
            return json(['code'=>0,'msg'=>'当前文件格式错误,仅支持XLSX文件']);
        }
        // if (!Lock::ins()->lock('handle:case:save:' . $this->request->fhUuid, 9)) {
        //     $this->error('请勿频繁操作');
        // }
        $caseNos = [];
        $fileData = FileLogic::ins()->getExeclCon($file->getPathname());
        
        foreach ($fileData as $key => $val) {
            if ($key <= 0) continue;
            $_val = trim($val[0]);
            if (empty($_val)) continue;
            $caseNos[$_val] = $val;
        }
        if (empty($caseNos)) {
            return json(['code'=>0,'msg'=>'未找到案件标识信息']);
        }
        // $result = FileLogic::ins()->saveCaseDetailData($caseNos); // 将要素信息保存到json文件中
        $insert_data = ['data_content'=>json_encode($caseNos, JSON_UNESCAPED_UNICODE)];
        $id = HandleProjectCases::where(['project_uuid' => $this->request->fhUuid])->value('id');
        if($id){
            $result =HandleProjectCases::where(['id' => $id])->update($insert_data);
        }else{
            $insert_data['project_uuid'] = $this->request->fhUuid;
            $result = HandleProjectCases::ins()->save($insert_data); // 将要素信息保存到数据库中
        }
        
        if ($result === false) {
            return json(errorMsg('保存案件要素信息失败'));
        }
        HandleProject::ins()->where(['uuid' => $this->request->fhUuid])->update(['case_total'=>(count($caseNos))]); // 更新案件总数
        return json(successMsg('保存案件要素信息成功'));
    }

    /**
     * 添加甲方和甲方清洗分类
     * @return \think\response\Json
     */
    public function addCompany()
    {
        $data = $this->request->post();
        try {
            $this->validate($data, [
                'name' => 'require|max:40', 
                'file_code' => 'require|array',
                'file_type' => 'require|array'
            ], [
                'name.require' => '公司名称不能为空', 
                'name.max' => '公司名称不能超过40个字符', 
                'file_code.require' => '请添加清洗文件的序号',
                'file_code.array' => '清洗文件序号参数类型错误',
                'file_type.require' => '请添加清洗文件类型',
                'file_type.array' => '清洗文件类型参数类型错误'
            ]);
        } catch (ValidateException $e) {
            // 验证失败，捕获异常
            return json(['code'=>0,'msg'=>$e->getError()]);   
        }
        $result = ProjectLogic::ins()->addCompany($data);
        return json($result);
    }

     /**
     * 获取甲方列表
     * @return \think\response\Json
     */
    public function getCompanyList()
    {
        $list = ProjectLogic::ins()->getCompanyList();
        return json($list);
    }

    /**
     * 修改甲方信息
     * @return \think\response\Json
     */
    public function editCompany()
    {
        $data = $this->request->post();
        try {
            $this->validate($data, [
                'id' => 'require|number', 
                'file_code' => 'require|array',
                'file_type' => 'require|array'
            ], [
                'id.require' => '公司ID不能为空', 
                'file_code.require' => '请添加清洗文件的序号',
                'file_code.array' => '清洗文件序号参数类型错误',
                'file_type.require' => '请添加清洗文件类型',
                'file_type.array' => '清洗文件类型参数类型错误'
            ]);
        } catch (ValidateException $e) {
            // 验证失败，捕获异常
            return json(['code'=>0,'msg'=> $e->getError()]);   
        }
        $result = ProjectLogic::ins()->editCompany($data);
        return json($result);
    }

}
